<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/04/11 20:58:15 $)
// $RCSfile: admin_parserrules.php,v $ : $Revision: 1.7 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

if (!$staffauth->isAdmin()) {
	trigger_error("You do not have permission to access $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/parser/functions_parser.php");
require_once ("./includes/functions_html.php");
$template->loadLanguageSection("staff_tickets");
$template->loadLanguageSection("mailparser_rules");
require_once ("./modules/parser/functions_parserrules.php");
require_once ("./modules/parser/functions_parserrulesui.php");
require_once ("./modules/tickets/tickets.php");

/**
* ###############################################
* FUNCTION DECLARATIONS
* ###############################################
*/


/**
* Callback for parsing rules data
*/
function _ruleFields($arg)
{
	global $_SWIFT;
	$record = &$arg[0];
	$fields = &$arg[1];

	$record["title"] = '<table width="100%"  border="0" cellspacing="0" cellpadding="1"><tr><td width="1"><img src="'. $_SWIFT["themepath"] .'icon_parserrules.gif" border="0" /></td><td><span class="smalltext">&nbsp;<a href="index.php?_m=parser&_a=editparserrule&parserruleid='. $record["parserruleid"] .'">'. htmlspecialchars($record["title"]) .'</a></span></td></tr></table>';

	$record["dateline"] = edate($_SWIFT["settings"]["dt_datetimeformat"], $record["dateline"]);
	$record["ruletype"] = iif($record["ruletype"]==RULE_PREPARSE, $_SWIFT["language"]["ipreparse"], $_SWIFT["language"]["ipostparse"]);

	$record["options"] = '<a href="index.php?_m=parser&_a=editparserrule&parserruleid='. $record["parserruleid"] .'" title="'. $_SWIFT["language"]["edit"] .'"><img src="'. $_SWIFT["themepath"] .'icon_edit.gif" border="0">&nbsp;'. $_SWIFT["language"]["edit"] .'</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onClick="javascript:doConfirm(\''. $_SWIFT["language"]["actionconfirm"] .'\', \'index.php?_m=parser&_a=managerules&do=delete&parserruleid='. $record["parserruleid"] .'\');" href="#" title="'. $_SWIFT["language"]["delete"] .'"><img src="'. $_SWIFT["themepath"] .'icon_delete.gif" border="0">&nbsp;'. $_SWIFT["language"]["delete"] .'</a>&nbsp;';
	return $record;
}

/**
* Mass Action: Delete Rules
*/
function _maDeleteRules()
{
	global $_SWIFT;

	if (!_is_array($_POST["itemid"]) || $_SWIFT["isdemo"] == true)
	{
		return false;
	}

	deleteParserRules($_POST["itemid"]);
}






/**
* ###############################################
* START VARIABLE DECLARATION
* ###############################################
*/

$_criteriapointer = array();
$_criteriapointer[PARSER_SENDERNAME]["title"] = $_SWIFT["language"]["p".PARSER_SENDERNAME];
$_criteriapointer[PARSER_SENDERNAME]["desc"] = $_SWIFT["language"]["desc_p".PARSER_SENDERNAME];
$_criteriapointer[PARSER_SENDERNAME]["op"] = "string";
$_criteriapointer[PARSER_SENDERNAME]["field"] = "text";

$_criteriapointer[PARSER_SENDEREMAIL]["title"] = $_SWIFT["language"]["p".PARSER_SENDEREMAIL];
$_criteriapointer[PARSER_SENDEREMAIL]["desc"] = $_SWIFT["language"]["desc_p".PARSER_SENDEREMAIL];
$_criteriapointer[PARSER_SENDEREMAIL]["op"] = "string";
$_criteriapointer[PARSER_SENDEREMAIL]["field"] = "text";

$_criteriapointer[PARSER_DESTINATIONNAME]["title"] = $_SWIFT["language"]["p".PARSER_DESTINATIONNAME];
$_criteriapointer[PARSER_DESTINATIONNAME]["desc"] = $_SWIFT["language"]["desc_p".PARSER_DESTINATIONNAME];
$_criteriapointer[PARSER_DESTINATIONNAME]["op"] = "string";
$_criteriapointer[PARSER_DESTINATIONNAME]["field"] = "text";

$_criteriapointer[PARSER_DESTINATIONEMAIL]["title"] = $_SWIFT["language"]["p".PARSER_DESTINATIONEMAIL];
$_criteriapointer[PARSER_DESTINATIONEMAIL]["desc"] = $_SWIFT["language"]["desc_p".PARSER_DESTINATIONEMAIL];
$_criteriapointer[PARSER_DESTINATIONEMAIL]["op"] = "string";
$_criteriapointer[PARSER_DESTINATIONEMAIL]["field"] = "text";

$_criteriapointer[PARSER_REPLYTONAME]["title"] = $_SWIFT["language"]["p".PARSER_REPLYTONAME];
$_criteriapointer[PARSER_REPLYTONAME]["desc"] = $_SWIFT["language"]["desc_p".PARSER_REPLYTONAME];
$_criteriapointer[PARSER_REPLYTONAME]["op"] = "string";
$_criteriapointer[PARSER_REPLYTONAME]["field"] = "text";

$_criteriapointer[PARSER_REPLYTOEMAIL]["title"] = $_SWIFT["language"]["p".PARSER_REPLYTOEMAIL];
$_criteriapointer[PARSER_REPLYTOEMAIL]["desc"] = $_SWIFT["language"]["desc_p".PARSER_REPLYTOEMAIL];
$_criteriapointer[PARSER_REPLYTOEMAIL]["op"] = "string";
$_criteriapointer[PARSER_REPLYTOEMAIL]["field"] = "text";

$_criteriapointer[PARSER_SUBJECT]["title"] = $_SWIFT["language"]["p".PARSER_SUBJECT];
$_criteriapointer[PARSER_SUBJECT]["desc"] = $_SWIFT["language"]["desc_p".PARSER_SUBJECT];
$_criteriapointer[PARSER_SUBJECT]["op"] = "string";
$_criteriapointer[PARSER_SUBJECT]["field"] = "text";

$_criteriapointer[PARSER_RECIPIENTS]["title"] = $_SWIFT["language"]["p".PARSER_RECIPIENTS];
$_criteriapointer[PARSER_RECIPIENTS]["desc"] = $_SWIFT["language"]["desc_p".PARSER_RECIPIENTS];
$_criteriapointer[PARSER_RECIPIENTS]["op"] = "string";
$_criteriapointer[PARSER_RECIPIENTS]["field"] = "text";

$_criteriapointer[PARSER_BODY]["title"] = $_SWIFT["language"]["p".PARSER_BODY];
$_criteriapointer[PARSER_BODY]["desc"] = $_SWIFT["language"]["desc_p".PARSER_BODY];
$_criteriapointer[PARSER_BODY]["op"] = "string";
$_criteriapointer[PARSER_BODY]["field"] = "text";

$_criteriapointer[PARSER_BODYSIZE]["title"] = $_SWIFT["language"]["p".PARSER_BODYSIZE];
$_criteriapointer[PARSER_BODYSIZE]["desc"] = $_SWIFT["language"]["desc_p".PARSER_BODYSIZE];
$_criteriapointer[PARSER_BODYSIZE]["op"] = "int";
$_criteriapointer[PARSER_BODYSIZE]["field"] = "int";

$_criteriapointer[PARSER_TEXTBODY]["title"] = $_SWIFT["language"]["p".PARSER_TEXTBODY];
$_criteriapointer[PARSER_TEXTBODY]["desc"] = $_SWIFT["language"]["desc_p".PARSER_TEXTBODY];
$_criteriapointer[PARSER_TEXTBODY]["op"] = "string";
$_criteriapointer[PARSER_TEXTBODY]["field"] = "text";

$_criteriapointer[PARSER_HTMLBODY]["title"] = $_SWIFT["language"]["p".PARSER_HTMLBODY];
$_criteriapointer[PARSER_HTMLBODY]["desc"] = $_SWIFT["language"]["desc_p".PARSER_HTMLBODY];
$_criteriapointer[PARSER_HTMLBODY]["op"] = "string";
$_criteriapointer[PARSER_HTMLBODY]["field"] = "text";

$_criteriapointer[PARSER_TEXTBODYSIZE]["title"] = $_SWIFT["language"]["p".PARSER_TEXTBODYSIZE];
$_criteriapointer[PARSER_TEXTBODYSIZE]["desc"] = $_SWIFT["language"]["desc_p".PARSER_TEXTBODYSIZE];
$_criteriapointer[PARSER_TEXTBODYSIZE]["op"] = "int";
$_criteriapointer[PARSER_TEXTBODYSIZE]["field"] = "int";

$_criteriapointer[PARSER_HTMLBODYSIZE]["title"] = $_SWIFT["language"]["p".PARSER_HTMLBODYSIZE];
$_criteriapointer[PARSER_HTMLBODYSIZE]["desc"] = $_SWIFT["language"]["desc_p".PARSER_HTMLBODYSIZE];
$_criteriapointer[PARSER_HTMLBODYSIZE]["op"] = "int";
$_criteriapointer[PARSER_HTMLBODYSIZE]["field"] = "int";

$_criteriapointer[PARSER_ATTACHMENTNAME]["title"] = $_SWIFT["language"]["p".PARSER_ATTACHMENTNAME];
$_criteriapointer[PARSER_ATTACHMENTNAME]["desc"] = $_SWIFT["language"]["desc_p".PARSER_ATTACHMENTNAME];
$_criteriapointer[PARSER_ATTACHMENTNAME]["op"] = "string";
$_criteriapointer[PARSER_ATTACHMENTNAME]["field"] = "text";

$_criteriapointer[PARSER_ATTACHMENTSIZE]["title"] = $_SWIFT["language"]["p".PARSER_ATTACHMENTSIZE];
$_criteriapointer[PARSER_ATTACHMENTSIZE]["desc"] = $_SWIFT["language"]["desc_p".PARSER_ATTACHMENTSIZE];
$_criteriapointer[PARSER_ATTACHMENTSIZE]["op"] = "int";
$_criteriapointer[PARSER_ATTACHMENTSIZE]["field"] = "int";

$_criteriapointer[PARSER_TOTALATTACHMENTSIZE]["title"] = $_SWIFT["language"]["p".PARSER_TOTALATTACHMENTSIZE];
$_criteriapointer[PARSER_TOTALATTACHMENTSIZE]["desc"] = $_SWIFT["language"]["desc_p".PARSER_TOTALATTACHMENTSIZE];
$_criteriapointer[PARSER_TOTALATTACHMENTSIZE]["op"] = "int";
$_criteriapointer[PARSER_TOTALATTACHMENTSIZE]["field"] = "int";

$_criteriapointer[PARSER_ISREPLY]["title"] = $_SWIFT["language"]["p".PARSER_ISREPLY];
$_criteriapointer[PARSER_ISREPLY]["desc"] = $_SWIFT["language"]["desc_p".PARSER_ISREPLY];
$_criteriapointer[PARSER_ISREPLY]["op"] = "bool";
$_criteriapointer[PARSER_ISREPLY]["field"] = "bool";

$_criteriapointer[PARSER_ISSTAFFREPLY]["title"] = $_SWIFT["language"]["p".PARSER_ISSTAFFREPLY];
$_criteriapointer[PARSER_ISSTAFFREPLY]["desc"] = $_SWIFT["language"]["desc_p".PARSER_ISSTAFFREPLY];
$_criteriapointer[PARSER_ISSTAFFREPLY]["op"] = "bool";
$_criteriapointer[PARSER_ISSTAFFREPLY]["field"] = "bool";

$_criteriapointer[PARSER_ISTHIRDPARTY]["title"] = $_SWIFT["language"]["p".PARSER_ISTHIRDPARTY];
$_criteriapointer[PARSER_ISTHIRDPARTY]["desc"] = $_SWIFT["language"]["desc_p".PARSER_ISTHIRDPARTY];
$_criteriapointer[PARSER_ISTHIRDPARTY]["op"] = "bool";
$_criteriapointer[PARSER_ISTHIRDPARTY]["field"] = "bool";

$_criteriapointer[PARSER_FLOODPROTECTION]["title"] = $_SWIFT["language"]["p".PARSER_FLOODPROTECTION];
$_criteriapointer[PARSER_FLOODPROTECTION]["desc"] = $_SWIFT["language"]["desc_p".PARSER_FLOODPROTECTION];
$_criteriapointer[PARSER_FLOODPROTECTION]["op"] = "bool";
$_criteriapointer[PARSER_FLOODPROTECTION]["field"] = "bool";

$_criteriapointer[PARSER_TICKETSTATUS]["title"] = $_SWIFT["language"]["p".PARSER_TICKETSTATUS];
$_criteriapointer[PARSER_TICKETSTATUS]["desc"] = $_SWIFT["language"]["desc_p".PARSER_TICKETSTATUS];
$_criteriapointer[PARSER_TICKETSTATUS]["op"] = "bool";
$_criteriapointer[PARSER_TICKETSTATUS]["field"] = "ticketstatusid";

/**
* ###############################################
* END VARIABLE DECLARATION
* ###############################################
*/







/**
* ###############################################
* START JS CODE
* ###############################################
*/
ob_start();
		?>
		<script type="text/javascript">
			var cruleindex = 1;
			function newRuleCriteria(crulename, selectedop, dfieldvalue)
			{
				var rowElement = document.createElement("div");
				rowElement.id = "rulerow"+cruleindex;
				var rowMod = cruleindex%2;
				rowElement.className = "searchrule"+rowMod;
				var tparent = browserObject("ruleparent");
				if (!tparent)
				{
					return false;
				}

				tparent.appendChild(rowElement);
				updateRuleHTML(cruleindex, crulename, selectedop, dfieldvalue);
				cruleindex++;
			}

			function removeRuleRow(ruleindex)
			{
				var tparent = browserObject("ruleparent");
				if (!tparent)
				{
					return false;
				}

				var rowElement = browserObject("rulerow"+ruleindex);
				if (!rowElement)
				{
					return false;
				}

				tparent.removeChild(rowElement);
			}

			function updateRuleHTML(ruleindex, fieldtype, selectedop, dfieldvalue)
			{
				var returnResult;

				returnResult = '<table border="0" cellpadding="3" cellspacing="1" width="100%"><tr><td align="left" width="1"><a href="javascript:void(0);" onClick="javascript:removeRuleRow(\''+ruleindex+'\');"><img src="<?=$_SWIFT["themepath"]?>icon_deletesmall.gif" border="0" /></a></td><td align="left" width="1"><select name="rulecriteria['+ ruleindex +'][0]" class="swiftselect" onChange="javascript:updateRuleHTML(\''+ ruleindex +'\', this.options[this.selectedIndex].value, 0, \'\');">';

				<?
				unset($rulefields);
				foreach ($_criteriapointer as $key=>$val)
				{
					?>returnResult += '<option value="<?=$key?>"'+selectedStatus(fieldtype, "<?=$key?>")+'><?=addslashes($val["title"])?></option>';
					<?
					$rulefields .= 'else if (fieldtype == "'. $key .'") {
					returnResult += getOperatorHTML(ruleindex, "'. $val["op"] .'", selectedop)+getQueryHTML(ruleindex, "'. $val["field"] .'", "'. addslashes($val["desc"]) .'", dfieldvalue);
				}';
				}
				?>
				returnResult += '</select>';

				returnResult += "</td>";

				if (1 == 2)
				{
				} <?=$rulefields;?>

				var dRow = browserObject("rulerow"+ruleindex);
				if (!dRow)
				{
					return;
				}

				dRow.innerHTML = returnResult+'</table>';
			}

			function selectedStatus(fieldtype, dfieldvalue)
			{
				if (fieldtype == dfieldvalue)
				{
					return " selected";
				}
			}

			function getOperatorHTML(ruleindex, optype, selectedop)
			{
				if (!ruleindex)
				{
					return;
				}

				if (optype == "string")
				{
					if (selectedop == "")
					{
						selectedop = <?=OP_CONTAINS?>;
					}
					return '<td align="left" width="130"><select name="rulecriteria['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_CONTAINS?>"'+ iif(selectedop == <?=OP_CONTAINS?>, " selected", "") +'><?=$_SWIFT["language"]["opcontains"]?></option><option value="<?=OP_NOTCONTAINS?>"'+ iif(selectedop == <?=OP_NOTCONTAINS?>, " selected", "") +'><?=addslashes($_SWIFT["language"]["opnotcontains"])?></option><option value="<?=OP_EQUAL?>"'+ iif(selectedop == <?=OP_EQUAL?>, " selected", "") +'><?=$_SWIFT["language"]["opequal"]?></option><option value="<?=OP_NOTEQUAL?>"'+ iif(selectedop == <?=OP_NOTEQUAL?>, " selected", "") +'><?=$_SWIFT["language"]["opnotequal"]?></option><option value="<?=OP_REGEXP?>"'+ iif(selectedop == <?=OP_REGEXP;?>, " selected", "") +'><?=$_SWIFT["language"]["opregexp"]?></option></select></td>';
				} else if (optype == "resstring") {
					if (selectedop == "")
					{
						selectedop = <?=OP_CONTAINS?>;
					}
					return '<td align="left" width="130"><select name="rulecriteria['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_CONTAINS?>"'+ iif(selectedop == <?=OP_CONTAINS?>, " selected", "") +'><?=$_SWIFT["language"]["opcontains"]?></option></select></td>';
				} else if (optype == "bool") {
					if (selectedop == "")
					{
						selectedop = <?=OP_EQUAL?>;
					}
					return '<td align="left" width="130"><select name="rulecriteria['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_EQUAL?>"'+ iif(selectedop == <?=OP_EQUAL?>, " selected", "") +'><?=$_SWIFT["language"]["opequal"]?></option><option value="<?=OP_NOTEQUAL?>"'+ iif(selectedop == <?=OP_NOTEQUAL?>, " selected", "") +'><?=$_SWIFT["language"]["opnotequal"]?></option></select></td>';
				} else if (optype == "int") {
					if (selectedop == "")
					{
						selectedop = <?=OP_EQUAL?>;
					}
					return '<td align="left" width="130"><select name="rulecriteria['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_GREATER?>"'+ iif(selectedop == <?=OP_GREATER?>, " selected", "") +'><?=$_SWIFT["language"]["opgreater"]?></option><option value="<?=OP_LESS?>"'+ iif(selectedop == <?=OP_LESS?>, " selected", "") +'><?=$_SWIFT["language"]["opless"]?></option><option value="<?=OP_EQUAL?>"'+ iif(selectedop == <?=OP_EQUAL?>, " selected", "") +'><?=$_SWIFT["language"]["opequal"]?></option><option value="<?=OP_NOTEQUAL?>"'+ iif(selectedop == <?=OP_NOTEQUAL?>, " selected", "") +'><?=$_SWIFT["language"]["opnotequal"]?></option></select></td>';
				} else if (optype == "cal") {
					if (selectedop == "")
					{
						selectedop = <?=OP_GREATER?>;
					}
					return '<td align="left" width="130"><select name="rulecriteria['+ ruleindex +'][1]" class="swiftselect"><option value="<?=OP_GREATER?>"'+ iif(selectedop == <?=OP_GREATER?>, " selected", "") +'><?=$_SWIFT["language"]["opgreater"]?></option><option value="<?=OP_LESS?>"'+ iif(selectedop == <?=OP_LESS?>, " selected", "") +'><?=$_SWIFT["language"]["opless"]?></option></select></td>';
				}
				
			}

			function getQueryHTML(ruleindex, querytype, pdesc, dfieldvalue)
			{
				if (!ruleindex)
				{
					return;
				}

				var returnResult = '<td align="left" width="100%">';
				if (querytype == "text")
				{
					returnResult += '<input type="text" size="20" class="swifttext" value="'+dfieldvalue+'" name="rulecriteria['+ ruleindex +'][2]" style="width:98%;" />';
				} else if (querytype == "int") {
					returnResult += '<input type="text" size="15" class="swifttext" value="'+dfieldvalue+'" name="rulecriteria['+ ruleindex +'][2]" />';
				} else if (querytype == "bool") {
					if (dfieldvalue == "")
					{
						dfieldvalue = "1";

					}
					returnResult += '<select name="rulecriteria['+ ruleindex +'][2]" class="swiftselect"><option value="1"'+iif(dfieldvalue=="1", " selected", "")+'><?=$_SWIFT["language"]["strue"]?></option><option value="0"'+ iif(dfieldvalue!="1", " selected", "") +'><?=$_SWIFT["language"]["sfalse"]?></option></select>';
				} else if (querytype == "ticketstatusid") {
					var dpselected = "";
					returnResult += '<select name="rulecriteria['+ ruleindex +'][2]" class="swiftselect">';
					<?
					foreach ($_SWIFT["statuscache"] as $key=>$val)
					{
						?>
						if (dfieldvalue == "<?=$val["ticketstatusid"]?>")
						{
							dpselected = " selected";
						} else {
							dpselected = "";
						}
						returnResult += '<option value="<?=$val["ticketstatusid"]?>" style="color:<?=$val["statuscolor"]?>;"'+ dpselected +'><?=addslashes($val["title"])?></option>';<?
					}
					?>
					returnResult += '</select>';
				}

				return returnResult+'</td></tr><tr><td colspan="4"><span class="smalltext">'+pdesc+'</span></td></tr>';
			}

			function switchRuleType(ruletype)
			{
				// Pre Parse
				if (ruletype == 1)
				{
					hideObject("departmentid"); hideObject("staffid"); hideObject("ticketstatusid"); hideObject("priorityid"); hideObject("flagtype"); hideObject("slaplanid"); hideObject("post7");
					displayObject("pre1"); displayObject("pre2"); displayObject("pre3"); displayObject("pre4"); displayObject("pre5"); displayObject("pre6");
				// Post Parse
				} else if (ruletype == 2) {
					hideObject("pre1"); hideObject("pre2"); hideObject("pre3"); hideObject("pre4"); hideObject("pre5"); hideObject("pre6");
					displayObject("departmentid"); displayObject("staffid"); displayObject("ticketstatusid"); displayObject("priorityid"); displayObject("flagtype"); displayObject("slaplanid"); displayObject("post7");
				}
			}
		</script>
		<?
$jscode = ob_get_contents();
ob_end_clean();
/**
* ###############################################
* END JS CODE
* ###############################################
*/





/**
* ###############################################
* INSERT PARSER RULE
* ###############################################
*/
if ($eventaction == "insertparserrule")
{
	if ($_POST["step"] == 1)
	{
		$_actions = processFormRuleActions();
		if (trim($_POST["title"]) == "" || !_is_array($_POST["rulecriteria"]) || !count($_actions))
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if ($_SWIFT["isdemo"] == true) {
			$errormessage = $_SWIFT["language"]["demomode"];
		} else {
			$_criteria = criteriaFormToArray();
			$parserruleid = insertParserRule($_POST["title"], $_POST["sortorder"], $_POST["ruletype"], iif($_POST["ruleoptions"] == "all", RULE_MATCHALL, RULE_MATCHANY), $_POST["stopprocessing"], $_criteria, $_actions);

			if ($parserruleid)
			{
				printRedirect(sprintf($_SWIFT["language"]["ruleinsertconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=parser&_a=managerules&insertrule=".urlencode($_POST["title"]));

				exit;
			}
		}
	}
	$ruletype = RULE_PREPARSE;

	$interface->adminHeader($_SWIFT["language"]["mailparser"]." > ".$_SWIFT["language"]["insertrule"], 1);

	$interface->adminNavBar('<a href="index.php?_m=parser&_a=manageemailqueues" title="'.$_SWIFT["language"]["mailparser"].'">'.$_SWIFT["language"]["mailparser"].'</a> &raquo; <a href="index.php?_m=parser&_a=managerules" title="'.$_SWIFT["language"]["managerules"].'">'.$_SWIFT["language"]["managerules"].'</a> &raquo; <a href="index.php?_m=parser&_a=insertparserrule" title="'.$_SWIFT["language"]["insertrule"].'">'.$_SWIFT["language"]["insertrule"]."</a>", $_SWIFT["language"]["desc_parserrules"] , 4);

	echo $jscode;

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderRuleForm(INSERT, $ruletype);

	?>
	<script type="text/javascript">
		newRuleCriteria('sendername', '<?=OP_CONTAINS?>', '');
		switchRuleType(<?=$ruletype?>);
	</script>
	<?

	$template->assign("backurl", "index.php?_m=parser&_a=managerules");
	$interface->adminFooter();




/**
* ###############################################
* EDIT PARSER RULE
* ###############################################
*/
} else if ($eventaction == "editparserrule") {
	$_parserrule = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."parserrules` WHERE `parserruleid` = '". intval($_REQUEST["parserruleid"]) ."';");
	if (empty($_parserrule["parserruleid"]))
	{
		trigger_error($_SWIFT["language"]["invalidrule"], E_USER_ERROR);
	}
	if ($_POST["step"] == 1)
	{
		$_actions = processFormRuleActions();
		if (trim($_POST["title"]) == "" || !_is_array($_POST["rulecriteria"]) || !count($_actions))
		{
			$errormessage = $_SWIFT["language"]["requiredfieldempty"];
		} else if ($_SWIFT["isdemo"] == true) {
			$errormessage = $_SWIFT["language"]["demomode"];
		} else {
			$_criteria = criteriaFormToArray();
			$result = updateParserRule($_parserrule["parserruleid"], $_POST["title"], $_POST["sortorder"], $_POST["ruletype"], iif($_POST["ruleoptions"] == "all", RULE_MATCHALL, RULE_MATCHANY), $_POST["stopprocessing"], $_criteria, $_actions);

			if ($result)
			{
				printRedirect(sprintf($_SWIFT["language"]["ruleupdateconfirm"], htmlspecialchars($_POST["title"])), "index.php?_m=parser&_a=managerules&updaterule=".urlencode($_POST["title"]));

				exit;
			}
		}
	}
	$ruletype = $_parserrule["ruletype"];
	$_POST = array_merge($_POST, $_parserrule);

	$_actions = $_criteria = array();
	// ======= GET CRITERIA =======
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."rulecriteria` WHERE `parserruleid` = '". intval($_parserrule["parserruleid"]) ."';");
	while ($dbCore->nextRecord())
	{
		$_criteria[$dbCore->Record["rulecriteriaid"]] = $dbCore->Record;
	}
	// ======= GET ACTIONS =======
	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."ruleactions` WHERE `parserruleid` = '". intval($_parserrule["parserruleid"]) ."';");
	while ($dbCore->nextRecord())
	{
		$_actions[$dbCore->Record["ruleactionid"]] = $dbCore->Record;
	}
	processRuleToFormActions($_actions);

	$interface->adminHeader($_SWIFT["language"]["mailparser"]." > ".$_SWIFT["language"]["editrule"], 1);

	$interface->adminNavBar('<a href="index.php?_m=parser&_a=manageemailqueues" title="'.$_SWIFT["language"]["mailparser"].'">'.$_SWIFT["language"]["mailparser"].'</a> &raquo; <a href="index.php?_m=parser&_a=managerules" title="'.$_SWIFT["language"]["managerules"].'">'.$_SWIFT["language"]["managerules"].'</a> &raquo; <a href="index.php?_m=parser&_a=editrule&parserruleid='. intval($_parserrule["parserruleid"]) .'" title="'.$_SWIFT["language"]["editrule"].'">'.$_SWIFT["language"]["editrule"]."</a>", $_SWIFT["language"]["desc_parserrules"] , 4);

	echo $jscode;

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	renderRuleForm(EDIT, $ruletype);

	?>
	<script type="text/javascript">
		<?
		echo criteriaArrayToForm($_criteria);
		?>
		switchRuleType(<?=$ruletype?>);
	</script>
	<?

	$template->assign("backurl", "index.php?_m=parser&_a=managerules");
	$interface->adminFooter();








/**
* ###############################################
* MANAGE PARSER RULES
* ###############################################
*/
} else if ($eventaction == "managerules") {
	if ($_GET["do"] == "delete" && $_GET["parserruleid"] != "" && $_SWIFT["isdemo"] != true)
	{
		$infomessage = $_SWIFT["ruledelconfirm"];
		deleteParserRules(array($_GET["parserruleid"]));
	}

	if (trim($_REQUEST["insertrule"]) != "")
	{
		$infomessage = sprintf($_SWIFT["language"]["ruleinsertconfirm"], $_REQUEST["insertrule"]);
	} else if (trim($_REQUEST["updaterule"]) != "") {
		$infomessage = sprintf($_SWIFT["language"]["ruleupdateconfirm"], $_REQUEST["updaterule"]);
	}

	$options["recordsperpage"] = "6";
	$options["sortby"] = "sortorder";
	$options["sortorder"] = "asc";
	$options["massaction"][0]["title"] = $_SWIFT["language"]["delete"];
	$options["massaction"][0]["callback"] = "_maDeleteRules";

	$options["idname"] = "parserruleid";
	$options["quicksearch"] = true;

	$options["advancedsearch"][0]["title"] = $_SWIFT["language"]["title"];
	$options["advancedsearch"][0]["query"] = 'SELECT * FROM `'. TABLE_PREFIX .'parserrules` WHERE `title` LIKE \'%$_searchstr%\' $_sortjoin;';

	$options["callback"] = "_ruleFields";

	$fields[0]["name"] = "title";
	$fields[0]["title"] = $_SWIFT["language"]["ruletitle"];
	$fields[0]["width"] = "";

	$fields[1]["name"] = "sortorder";
	$fields[1]["title"] = $_SWIFT["language"]["sortorder"];
	$fields[1]["width"] = "120";
	$fields[1]["align"] = "center";

	$fields[2]["name"] = "ruletype";
	$fields[2]["title"] = $_SWIFT["language"]["ruletype"];
	$fields[2]["width"] = "180";
	$fields[2]["align"] = "center";

	$fields[3]["name"] = "dateline";
	$fields[3]["title"] = $_SWIFT["language"]["creationdate"];
	$fields[3]["width"] = "200";
	$fields[3]["align"] = "center";

	$fields[4]["type"] = "custom";
	$fields[4]["name"] = "options";
	$fields[4]["title"] = $_SWIFT["language"]["options"];
	$fields[4]["width"] = "120";
	$fields[4]["align"] = "center";

	$grid = new Grid();

	$interface->adminHeader($_SWIFT["language"]["mailparser"]." > ".$_SWIFT["language"]["managerules"], 1);

	$interface->adminNavBar('<a href="index.php?_m=parser&_a=manageemailqueues" title="'.$_SWIFT["language"]["mailparser"].'">'.$_SWIFT["language"]["mailparser"].'</a> &raquo; <a href="index.php?_m=parser&_a=managerules" title="'.$_SWIFT["language"]["managerules"].'">'.$_SWIFT["language"]["managerules"]."</a>", $_SWIFT["language"]["desc_parserrules"] , 4);

	printInfoBox($infomessage);
	printErrorBox($errormessage);

	$grid->start("prules", $_SWIFT["language"]["rulelist"], 'SELECT * FROM `'. TABLE_PREFIX .'parserrules` $_sortjoin;', 'SELECT COUNT(*) AS totalitems FROM `'. TABLE_PREFIX .'parserrules`;', 'SELECT * FROM `'. TABLE_PREFIX .'parserrules` WHERE `title` LIKE \'%$_searchstr%\' $_sortjoin;', $fields, $options);
	$grid->display("prules");

	$template->assign("backurl", "index.php?_m=parser&_a=manageemailqueues");
	$interface->adminFooter();
}
?>